﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Text;
using System.Collections.Generic;
using System.Threading;

public partial class BookingNote_BookingNoteLook :BasePage
{

    IRolePurviewHandler userManage = new RolePurviewHandler();
    ISyClientHandler clientManage = new SyClientHandler();
    ISyMarketHandler markManage = new SyMarketHandler();
    ISyPlaceHandler placeManage = new SyPlaceHandler();
    ISyDestinationHandler destManage = new SyDestinationHandler();
    IBNBookingNoteHandler bookingNoteManage = new BNBookingNoteHandler();
    ISystemHandler systemManage = new SystemHandler();
    private static string clientName = string.Empty;
    private static string bnDetailID = string.Empty;
    private static bool isCheck = false;
    private static bool isCancel = false;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                ISystemHandler sysManage = new SystemHandler();
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!(strPermission.Contains("1053")))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }

                else
                {
                    //判断用户有没有审核托运单权限
                    if (strPermission.Contains("1057"))
                    {
                       // btnCheck.Visible = true;
                       // isCheck = true;
                    }
                    else
                    {
                      //  btnCheck.Visible = false;
                      //  isCheck = false;
                    }

                    //判断用户有没有取消托运单权限
                    if (strPermission.Contains("1058"))
                    {
                     //   btnCancel.Visible = true;
                     //   isCancel = true;
                    }
                    else
                    {
                      //  btnCancel.Visible = false;
                       // isCancel = false;
                    }
                }
            } 
          
            ViewState["OrderBy"] = "PKID";
            ViewState["Accending"] = "desc";
            FillDDl();            
            dataBind();
           
        }
    }

    private void dataBind()
    {
        if (Request["BookingNoteID"] != null)
        {
            BN_BookingNoteQuery bnQuery = bookingNoteManage.GetBookingNoteByPKID(int.Parse(Request["BookingNoteID"]));
            if (bnQuery != null)
            {
                if (isCheck && isCancel)
                {
                    if (bnQuery.Status.ToString() == Enums.BookingNoteStatus.NEW.ToString("d") || bnQuery.Status.ToString() == Enums.BookingNoteStatus.CANCEL.ToString("d"))
                    {
                        btnCheck.Visible = true;
                        btnCancel.Visible = false;
                    }
                    else
                    {
                        btnCheck.Visible = false;
                        btnCancel.Visible = true;
                    }
                }
                else if (isCheck == true && isCancel == false)
                {
                    if (bnQuery.Status.ToString() == Enums.BookingNoteStatus.NEW.ToString("d") || bnQuery.Status.ToString() == Enums.BookingNoteStatus.CANCEL.ToString("d"))
                    {
                        btnCheck.Visible = true;
                    }
                    else
                    {
                        btnCheck.Visible = false;
                    }
                }
                else if (isCheck == false && isCancel == true)
                {
                    if (bnQuery.Status.ToString() == Enums.BookingNoteStatus.NEW.ToString("d") || bnQuery.Status.ToString() == Enums.BookingNoteStatus.CANCEL.ToString("d"))
                    {
                        btnCancel.Visible = true;
                    }
                    else
                    {
                        btnCancel.Visible = false;
                    }
                }

                txtPoNO.Text = bnQuery.PoNO;
                ddlShipper.SelectedValue = bnQuery.ShipperID.ToString();
                BindShipperLM(bnQuery.ShipperID);
                ddlShipperLM.SelectedValue = bnQuery.ShipperLMID.ToString();
                txtInvoiceNO.Text = bnQuery.InvoiceNO;
                txtPcNO.Text = bnQuery.PcNO;
                if (bnQuery.WinStart != DateTime.MinValue)
                {
                    txtWinStart.Text = bnQuery.WinStart.ToString("yyyy-MM-dd");
                }
                if (bnQuery.WinClose != DateTime.MinValue)
                {
                    txtWinClose.Text = bnQuery.WinClose.ToString("yyyy-MM-dd");
                }
                if (bnQuery.WinLastClose != DateTime.MinValue)
                {
                    txtWinLastClose.Text = bnQuery.WinLastClose.ToString("yyyy-MM-dd");
                }
                ddlCustomer.SelectedValue = bnQuery.CustomerID.ToString();
                ddlMarket.SelectedValue = bnQuery.MarketID.ToString();
                ddlDestination.SelectedValue = bnQuery.DestinationID.ToString();
                ddlCarrierForwar.SelectedValue = bnQuery.CarrierForwar.ToString();
                txVV.Text = bnQuery.VV.ToString();

                txtJobNum.Text = bnQuery.JobNumber;
                txtSourceCodes.Text = bnQuery.SourceCode;

                if (bnQuery.SICutOFFDate != DateTime.MinValue)
                {
                    txtSICutOFFDate.Text = bnQuery.SICutOFFDate.ToString("yyyy-MM-dd");
                }
                txtCPO.Text = bnQuery.CPO.ToString();
                txtRemark.Text = bnQuery.Remark.ToString();
                if (bnQuery.CreatedDate != DateTime.MinValue)
                {
                    txtCreatedDate.Text = bnQuery.CreatedDate.ToString("yyyy-MM-dd HH:mm:ss");
                }
                
                txtCreatedUser.Text = GetUserName(bnQuery.CreatedUser);
                if (bnQuery.LastModDate != DateTime.MinValue)
                {
                    txtLastModDate.Text = bnQuery.LastModDate.ToString("yyyy-MM-dd HH:mm:ss");
                }
                txtLastModUser.Text = GetUserName(bnQuery.LastModUser);

                txtStatus.Text = StringUtil.GetBnStatus(bnQuery.Status);
              
                if (bnQuery.CheckedDate != DateTime.MinValue)
                {
                    txtCheckedDate.Text = bnQuery.CheckedDate.ToString("yyyy-MM-dd HH:mm:ss");
                }
                if (bnQuery.CancelDate != DateTime.MinValue)
                {
                    txtCancelDate.Text = bnQuery.CancelDate.ToString("yyyy-MM-dd HH:mm:ss");
                }

            }
            dataBindDetail(Request["BookingNoteID"]);

        }
    }

  

    private void dataBindDetail(string bookingNoteID)
    {
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@BookingNoteID", bookingNoteID);
        string sqlStr = "select * from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID ";

        DataTable dt = bookingNoteManage.GetBookingNoteDetailList(sqlStr, parms);
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
        gvBookNoteDetailList.DataSource = view;
        gvBookNoteDetailList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotal.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotal.Text = "0";
        }
    }

    private void FillDDl()
    {
        //绑定托运人
        DataTable dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.TYR.ToString("d")));
        ddlShipper.DataSource = dt;

        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlShipper.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlShipper.DataTextField = "HKShortName";
        }
        else
        {
            ddlShipper.DataTextField = "CNShortName";
        }
        ddlShipper.DataValueField = "PKID";
        ddlShipper.DataBind();
        ddlShipper.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

        //客户客人
        dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.KHKR.ToString("d")));
        ddlCustomer.DataSource = dt;
        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlCustomer.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlCustomer.DataTextField = "HKShortName";
        }
        else
        {
            ddlCustomer.DataTextField = "CNShortName";
        }
        ddlCustomer.DataValueField = "PKID";
        ddlCustomer.DataBind();
        ddlCustomer.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

        //市场
        dt = markManage.GetList();
        ddlMarket.DataSource = dt;
        ddlMarket.DataTextField = "CNName";
        ddlMarket.DataValueField = "PKID";
        ddlMarket.DataBind();
        ddlMarket.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

        //目的地
        dt = destManage.GetList();
        ddlDestination.DataSource = dt;
        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlDestination.DataTextField = "ENGName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlDestination.DataTextField = "HKName";
        }
        else
        {
            ddlDestination.DataTextField = "CNName";
        }
        ddlDestination.DataValueField = "PKID";
        ddlDestination.DataBind();
        ddlDestination.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

               


        //船公司/货代
        SqlParameter[] parms = new SqlParameter[3];
        parms[0] = new SqlParameter("@TypeID", Enums.CT.CGS.ToString("d"));
        parms[1] = new SqlParameter("@Status", "1");
        parms[2] = new SqlParameter("@TypeID2", Enums.CT.HD.ToString("d"));
        string sqlStr = "select * from Sy_Client where PKID in(select ClientID from Sy_ClientType where SyCodeID=@TypeID OR SyCodeID=@TypeID2) and Status=@Status";

        dt = clientManage.GetClientList(sqlStr, parms);
        ddlCarrierForwar.DataSource = dt;
        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlCarrierForwar.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlCarrierForwar.DataTextField = "HKShortName";
        }
        else
        {
            ddlCarrierForwar.DataTextField = "CNShortName";
        }
        ddlCarrierForwar.DataValueField = "PKID";
        ddlCarrierForwar.DataBind();
        ddlCarrierForwar.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));
    }


    private void BindShipperLM(int clientID)
    {

        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@ClientID", clientID.ToString());
        string sqlStr = "select * from Sy_ClientLinkMan where ClientID =@ClientID";
        DataTable dt = clientManage.GetClientLinkManList(sqlStr, parms);
        ddlShipperLM.DataSource = dt;
        ddlShipperLM.DataTextField = "LinkMan";
        ddlShipperLM.DataValueField = "PKID";
        ddlShipperLM.DataBind();
        ddlShipperLM.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

    }

    public string GetClientLinkMan(object cLinkMan)
    {
        string name = string.Empty;
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@PKID", cLinkMan.ToString());
        string sqlStr = "select * from Sy_ClientLinkMan where PKID =@PKID";
        DataTable dt = clientManage.GetClientLinkManList(sqlStr, parms);
        if (dt != null && dt.Rows.Count > 0)
        {
            name = dt.Rows[0]["LinkMan"].ToString();
        }
        return name;
    }
        
    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvBookNoteDetailList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvBookNoteDetailList.PageCount)
            {
                this.gvBookNoteDetailList.PageIndex = i;
                //数据绑定
                dataBind();
            }
            else
            {
                // Jscript.AlertInAjax("请输入大于0小于总页数的正整数!", UpdatePanel1);
                Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
                return;
            }
        }
        catch
        {
            // Jscript.AlertInAjax("请输入大于0小于总页数的正整数!", UpdatePanel1);
            Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);

        }
    }
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvBookNoteDetailList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBindDetail(Request["BookingNoteID"]);
    }

    protected void gvBookNoteDetailList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvBookNoteDetailList.PageIndex = e.NewPageIndex;
        dataBindDetail(Request["BookingNoteID"]);
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("BookingNoteList.aspx");
    }

    protected void btnCheck_Click(object sender, EventArgs e)
    {
        BN_BookingNoteQuery bnQuery = bookingNoteManage.GetBookingNoteByPKID(int.Parse(Request["BookingNoteID"]));
        if (bnQuery != null)
        {
            if (bnQuery.Status.ToString() == Enums.BookingNoteStatus.NEW.ToString("d") || bnQuery.Status.ToString() == Enums.BookingNoteStatus.CANCEL.ToString("d") )
            {
                string strSql = "update BN_BookingNote set Status=@Status,CheckedDate=@CheckedDate where PKID=@BookingNoteID";
                SqlParameter[] parms = new SqlParameter[3];
                parms[0] = new SqlParameter("@BookingNoteID", Request["BookingNoteID"]);
                parms[1] = new SqlParameter("@Status", Enums.BookingNoteStatus.CHECK.ToString("d"));
                parms[2] = new SqlParameter("@CheckedDate",DateTime.Now);
                if (bookingNoteManage.BookingNoteUpdate(strSql, parms))
                {
                    Jscript.AlertAndRedirectInAjax(Resources.Messages.CheckSuccess, "BookingNoteList.aspx", UpdatePanel1);
                }
                else
                {
                    Jscript.AlertInAjax(Resources.Messages.CheckFailed, UpdatePanel1);
                }
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.AlreadyCheck, UpdatePanel1);
            }
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        BN_BookingNoteQuery bnQuerys = bookingNoteManage.GetBookingNoteByPKID(int.Parse(Request["BookingNoteID"]));
        if (bnQuerys != null)
        {
            if (bnQuerys.Status.ToString() == Enums.BookingNoteStatus.CHECK.ToString("d"))
            {
                SqlParameter[] parms = new SqlParameter[1];
                parms[0] = new SqlParameter("@BookingNoteID", bnQuerys.PKID.ToString());
                string sqlStr = "select * from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID";
                DataTable dtBND = bookingNoteManage.GetBookingNoteDetailList(sqlStr, parms);
                if (dtBND != null && dtBND.Rows.Count > 0)
                {
                    bool istrue = false;
                    for (int i = 0; i < dtBND.Rows.Count; i++)
                    {
                        if (dtBND.Rows[i]["Status"].ToString() != Enums.BookingNoteDtlStatus.NEW.ToString("d") && dtBND.Rows[i]["Status"].ToString() != Enums.BookingNoteDtlStatus.CANCELBOOKING.ToString("d"))
                        {
                            istrue = true;
                            break;
                        }
                    }
                    if (istrue)
                    {
                        Jscript.AlertInAjax("该托运单的详细单状态不为新增或取消Booking,不能取消!", UpdatePanel1);
                        return;
                    }
                    else
                    {
                        SqlParameter[] parmsCancel = new SqlParameter[3];
                        parmsCancel[0] = new SqlParameter("@BookingNoteID", bnQuerys.PKID.ToString());
                        parmsCancel[1] = new SqlParameter("@Status",Enums.BookingNoteStatus.CANCEL.ToString("d"));
                        parmsCancel[2] = new SqlParameter("@CancelDate", DateTime.Now);
                        sqlStr = "update BN_BookingNote set Status=@Status, CancelDate=@CancelDate where PKID=@BookingNoteID";
                        if (bookingNoteManage.BookingNoteUpdate(sqlStr, parmsCancel))
                        {
                            Jscript.AlertAndRedirectInAjax("取消托运单成功!","BookingNoteList.aspx", UpdatePanel1);
                        }
                        else
                        {
                            Jscript.AlertInAjax("取消托运单失败!", UpdatePanel1);
                        }
                    }
                }
            }
            else
            {
                Jscript.AlertInAjax("该托运单已不为审核状态!", UpdatePanel1);
                return;
            }
        }
    }
        

    public string GetClient(object id)
    {
      return systemManage.GetClient(id);
    }

    public string GetPlace(object id)
    {
        return systemManage.GetPlace(id);
    }

    public string GetUserName(object userID)
    {
        return systemManage.GetUserName(userID);
    }
    protected void gvBookNoteDetailList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBindDetail(Request["BookingNoteID"]);
    }
}
